define(function (require, exports, module) {
    'use strict';

    var rk = require('rk');
    require('../../../xsyBase');

    $.widget('rk.xsyOpportunityProgress', $.rk.xsyBase, {
        options: {},
        _create: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            me._beIniting();

            me.mapClassName = {
                'doc': 'xsy_opportunity_progress_word',
                'docx': 'xsy_opportunity_progress_word',
                'xls': 'xsy_opportunity_progress_excel',
                'xlsx': 'xsy_opportunity_progress_excel',
                'ppt': 'xsy_opportunity_progress_ppt',
                'pptx': 'xsy_opportunity_progress_ppt',
                'pdf': 'xsy_opportunity_progress_pdf',
                'txt': 'xsy_opportunity_progress_txt'
            };

            me.bindEventHandler();
        },
        _init: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            me.reload();
        },
        reload: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            me._loadData({}, function (result) {
                // result.uuid 控件的uuid
                // result.common 页面公共的数据
                // result.self 控件自己的数据
                me.selfData = result.self;
                elem.addClass('xsy_listpreview FULL');
                if (me.selfData.stages.length < 1) {
                    return;
                }
                if (!result.self.hasBusinessProcessFunction) {
                    //简单流程
                    if (!me.selfData.currentStage) {
                        me.selfData.currentStage = me.selfData.stages[0];
                    }
                    if (me.selfData.currentStage.id == me.selfData.failureStage.id && !me.selfData.lostStage) {
                        me.selfData.lostStage = me.selfData.stages[0];
                    }
                    me.selfData.currentIndex = 0;
                    $.each(me.selfData.stages, function (_stageIndex, _stage) {
                        if (me.selfData.currentStage.id != me.selfData.failureStage.id && _stage.id == me.selfData.currentStage.id) {
                            me.selfData.currentIndex = _stageIndex;
                        }
                        if (me.selfData.currentStage.id == me.selfData.failureStage.id && _stage.id == me.selfData.lostStage.id) {
                            me.selfData.currentIndex = _stageIndex;
                        }
                    });
                    elem.html(rk.templateText(require('platform/widgets/crm/opportunity/xsyOpportunityProgress/simple_progress.tpl'), result.self));
                } else {
                    //复杂流程
                    if (!me.selfData.currentStage) {
                        me.selfData.currentStage = me.selfData.stages[0].id;
                    }
                    if (me.selfData.currentStage == me.selfData.failureStage.id && !me.selfData.lostStage) {
                        me.selfData.lostStage = me.selfData.stages[0].id;
                    }
                    if (me.selfData.currentStage == me.selfData.failureStage.id) {
                        me.selfData.failureFlg = 1;
                        me.selfData.currentStage = me.selfData.lostStage;
                    }
                    $.each(me.selfData.stages, function (_stageIndex, _stage) {
                        if (_stage.id == me.selfData.currentStage) {
                            me.selfData.currentStage = _stage;
                        }
                    });
                    me._renderComplexProgress();
                }
            }, function () {
                console.log('loading data error');
            });
        },
        _renderComplexProgress: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me.selfData.currentIndex = 0;
            me.selfData.currentStageIndex = 0;
            $.each(me.selfData.stages, function (_stageIndex, _stage) {
                if (_stage.id == me.selfData.currentStage.id) {
                    me.selfData.currentStageIndex = _stageIndex;
                    if (me.selfData.currentStage.id != me.selfData.failureStage.id) {
                        me.selfData.currentIndex = _stageIndex;
                    }
                }
                if (me.selfData.currentStage.id == me.selfData.failureStage.id && _stage.id == me.selfData.lostStage.id) {
                    me.selfData.currentIndex = _stageIndex;
                }
            });
            var prevStagePercent = 0;
            me.selfData.stages = $.map(me.selfData.stages, function (_stage) {
                if (_stage.stageStatus == 1) {
                    _stage.currentPercent = _stage.percent;
                } else {
                    _stage.currentPercent = prevStagePercent;
                    $.each(_stage.activities, function (_activityIndex, _activity) {
                        if (_activity.checked == 1) {
                            _stage.currentPercent += _activity.percent;
                        }
                    });
                }
                prevStagePercent = _stage.percent;
                $.each(_stage.activities, function (_activityIndex, _activity) {
                    _activity.fileType = ((_activity.fileName != null) ? (me.mapClassName[_activity.fileName.split('.').pop()] || 'xsy_opportunity_progress_txt') : 'xsy_opportunity_progress_txt');
                });
                return _stage;
            });
            elem.html(rk.templateText(require('platform/widgets/crm/opportunity/xsyOpportunityProgress/complex_progress.tpl'), me.selfData));
            //遍历所有阶段，正确展示各小阶段样式
            $.each(me.selfData.stages, function (_stageIndex, _stage) {
                var stageSuffix = '[stageId=' + _stage.id + ']';
                var $progressCard = elem.find('div.xsy_opportunity_progress_card' + stageSuffix);

                $.each(_stage.activities, function (_activityIndex, _activity) {
                    var activitySuffix = '[activityId=' + _activity.id + ']';
                    var $progressCardItem = $progressCard.find('li.xsy_opportunity_progress_carditem' + activitySuffix);
                    var $progressFlow = $progressCardItem.find('div.xsy_opportunity_progress_flow');
                    var $checkbox = $progressCardItem.find('a.xsy_opportunity_progress_flow_ico');

                    if (_stageIndex <= me.selfData.currentIndex) {
                        if (_activity.checked == 1) {
                            $progressFlow.addClass("xsy_opportunity_progress_flowdone");
                        }
                    } else if (_stageIndex == me.selfData.currentIndex + 1 && me.selfData.currentStage.stageStatus == 0) {
                        $progressFlow.addClass("xsy_opportunity_progress_flowdisabled");
                    } else if (_stageIndex > me.selfData.currentIndex + 1) {
                        $progressFlow.addClass("xsy_opportunity_progress_flowdisabled");
                    }
                    if ((me.selfData.currentStage.id == _stage.id) || (me.selfData.currentStageIndex + 1 == _stageIndex && me.selfData.currentStage.stageStatus == 1)) {
                        if (_activity.checked == 0) {
                            if (_activity.keyFlag == 1 && _activity.fileId == '') {
                                $checkbox.addClass("xsy_opportunity_progress_flow_disabled");
                                $checkbox.addClass("js-can-upload");
                            } else {
                                $checkbox.addClass("xsy_opportunity_progress_flow_normal");
                            }
                        } else if (_activity.checked == 1) {
                            $checkbox.addClass("xsy_opportunity_progress_flow_done");
                        }
                    } else {
                        if (_activity.checked == 0) {
                            $checkbox.addClass("xsy_opportunity_progress_flow_disabled");
                        } else if (_activity.checked == 1) {
                            $checkbox.addClass("xsy_opportunity_progress_flow_disabledcheck");
                        }
                    }
                });
            });
            elem.find('li.js-complex-progress[stageId=' + me.selfData.viewStageId + ']').trigger('click');
        },
        bindEventHandler: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            elem.on("click", "a[jsFooterA]", function () {
                var $lnk = $(this);
                var $progressBody = elem.find('div.xsy_opportunity_progress_body');
                $lnk.hide();
                if ($lnk.attr("jsFooterA") == 1) {
                    $lnk.next().show();
                    $progressBody.slideUp();
                } else if ($lnk.attr("jsFooterA") == 2) {
                    $lnk.prev().show();
                    $progressBody.slideDown();
                }
            });

            //简单流程
            elem.on("click", "a.js-simple-progress,li.js-simple-progress", function () {
                var $lnk = $(this);
                //无修改权限不让点
                if (!me.selfData.canUpdate) {
                    return false;
                }
                //输单状态其它按钮不让点
                if((me.selfData.currentStage.id == me.selfData.failureStage.id) && !$lnk.attr('canClick')){
                    return false;
                }
                var _oppId = me._getCommonData().id;
                var $status = $lnk.attr("status");
                if ($status == 1) {
                    var doActive = function () {
                        $.postJson('/json/crm_opportunity/update-stage.action', {
                            opportunityId: _oppId,
                            stageId: $lnk.attr('stageId')
                        }).done(function (json) {
                            if (json.status == 0 || json.status == 1001) {
                                me.reload();
                            } else {
                                $.msg(rk.i18n('CRM_CORE_MODIFY') + rk.i18n('CRM_CORE_FAILED'));
                            }
                        });
                    }
                    var needConfirm = me.selfData.currentStage.id == me.selfData.failureStage.id;
                    if (needConfirm) {
                        $.confirm(rk.i18n('OPPORTUNITY_ACTIVE_CONFIRM'), doActive);
                    } else {
                        doActive();
                    }
                } else if ($status == 2) {
                    var needConfirm = me.selfData.currentStage.status != 2;
                    var doWin = function () {
                        $.postJson('/json/crm_opportunity/update-stage.action', {
                            opportunityId: _oppId,
                            stageId: $lnk.attr('stageId')
                        }).done(function (json) {
                            if (json.status == 0 || json.status == 1001) {
                                me.reload();
                                if(needConfirm){
                                    me._triggerOuterEvent('afterPopupEdit');
                                }
                            } else {
                                $.msg(rk.i18n('CRM_CORE_MODIFY') + rk.i18n('CRM_CORE_FAILED'));
                            }
                        });
                    }
                    if (needConfirm) {
                        $.confirm(rk.i18n('OPPORTUNITY_WIN_CONFIRM'), doWin);
                    } else {
                        doWin();
                    }
                } else if ($status == 3) {
                    var reasonItem = $.map(me.selfData.failureReasons, function (o, i) {
                        return ['<option value="', o.id, '">', o.name, '</option>'].join('');
                    }).join('');
                    var oppName = me._getCommonData().name;
                    var $dialog = $($.format($.trim(require('platform/widgets/crm/opportunity/xsyOpportunityProgress/add_lose_reason.tpl')), {
                        oppName: oppName,
                        reasonItem: reasonItem
                    }));
                    var $reason = $dialog.find('select#loseReason');
                    $dialog.popup({
                        width: 320,
                        hieght: 200,
                        title: rk.i18n('OPPORTUNITY_LOSE'),
                        actions: {
                            save: function (evt, dialog) {
                                var r = $reason.val();
                                if (r) {
                                    $.postJson('/json/crm_opportunity/update-stage.action', {
                                        reason: r,
                                        opportunityId: _oppId,
                                        stageId: $lnk.attr('stageId')
                                    }).done(function (json) {
                                        if (json.status == 0 || json.status == 1001) {
                                            dialog.close();
                                            me.reload();
                                        } else {
                                            $.msg(rk.i18n('CRM_CORE_MODIFY') + rk.i18n('CRM_CORE_FAILED'));
                                        }
                                    });
                                } else {
                                    $.msg(rk.i18n('OPPORTUNITY_LOSE_CONDITION_FAILED'));
                                }
                            }
                        },
                        create: function () {

                        }
                    });
                }
            });

            //复杂流程
            elem.on("click", "li.js-complex-progress", function () {
                var $lnk = $(this);
                var stageId = $lnk.attr('stageId');
                elem.find('li.js-complex-progress').removeClass('visited');
                $lnk.addClass('visited');
                elem.find('div.xsy_opportunity_progress_card').hide();
                elem.find('div.xsy_opportunity_progress_card[stageId=' + stageId + ']').show();
            });

            //复杂流程关闭
            elem.on("click", "a.js-complex-progress", function () {
                //无修改权限不让点
                if (!me.selfData.canUpdate) {
                    return false;
                }
                var $lnk = $(this);
                var $status = $lnk.attr("status");
                var _oppId = me._getCommonData().id;
                if ($status == 2) {
                    $.confirm(rk.i18n('OPPORTUNITY_ACTIVE_CONFIRM'), function () {
                        $.postJson("/json/crm_opportunity/active.action", {"opportunityId": _oppId}, function (data) {
                            var dataJson = (data);
                            if (dataJson.status == 0) {
                                me.reload();
                            } else {
                                $.msg(rk.i18n('CRM_CORE_OPERATE') + rk.i18n('CRM_CORE_FAILED'), 0);
                            }
                        });
                    });
                } else if ($status == 3) {
                    var reasonItem = $.map(me.selfData.failureReasons, function (o, i) {
                        return ['<option value="', o.id, '">', o.name, '</option>'].join('');
                    }).join('');
                    var oppName = me._getCommonData().name;
                    var $dialog = $($.format($.trim(require('platform/widgets/crm/opportunity/xsyOpportunityProgress/add_lose_reason.tpl')), {
                        oppName: oppName,
                        reasonItem: reasonItem
                    }));
                    var $reason = $dialog.find('select#loseReason');
                    $dialog.popup({
                        width: 320,
                        hieght: 200,
                        title: rk.i18n('OPPORTUNITY_LOSE'),
                        actions: {
                            save: function (evt, dialog) {
                                var r = $reason.val();
                                if (r) {
                                    $.postJson('/json/crm_opportunity/lose.action', {
                                        reason: r,
                                        opportunityId: _oppId
                                    }).done(function (json) {
                                        if (json.status == 0) {
                                            dialog.close();
                                            me.reload();
                                        } else {
                                            $.msg(rk.i18n('CRM_CORE_MODIFY') + rk.i18n('CRM_CORE_FAILED'));
                                        }
                                    });
                                } else {
                                    $.msg(rk.i18n('OPPORTUNITY_LOSE_CONDITION_FAILED'));
                                }
                            }
                        },
                        create: function () {

                        }
                    });
                }
            });

            //点击复选框
            var saveActivitySettingUrl = "/json/crm_opportunity/save-activity-setting.action";
            elem.on("click", "a.xsy_opportunity_progress_flow_ico", function () {
                //无修改权限不让点
                if (!me.selfData.canUpdate) {
                    return false;
                }
                //输单状态其它按钮不让点
                if(me.selfData.failureFlg == 1){
                    return false;
                }
                var $lnk = $(this);
                if (!$lnk.hasClass("xsy_opportunity_progress_flow_done") && !$lnk.hasClass("xsy_opportunity_progress_flow_normal")) {
                    return false;
                }
                var $stageDiv = $lnk.closest('div[stageId]');
                var $activityLi = $lnk.closest('li[activityId]');
                var postStageId = $stageDiv.attr('stageId');
                var winRate = 0;
                var needConfirm = 0;
                $.each(me.selfData.stages, function (_stageIndex, _stage) {
                    var stageStatus = 1;
                    var allUnChecked = 1;
                    $.each(_stage.activities, function (_activityIndex, _activity) {
                        if (_activity.id == $activityLi.attr('activityId')) {
                            if ($lnk.attr('hasChecked') == 1) {
                                stageStatus = 0;
                            } else {
                                winRate = winRate + _activity.percent;
                                allUnChecked = 0;
                            }
                        } else {
                            if (_activity.checked == 0) {
                                stageStatus = 0;
                            }
                            if (_activity.checked == 1) {
                                winRate = winRate + _activity.percent;
                                if (_activity.keyFlag == 1 && _activity.fileId == '') {
                                    stageStatus = 0;
                                }
                                allUnChecked = 0;
                            }
                        }
                    });
                    if (_stage.id == $stageDiv.attr('stageId')) {
                        if (stageStatus && _stage.status == 2) {
                            needConfirm = 1;
                        }
                        if (allUnChecked && _stageIndex > 0) {
                            postStageId = me.selfData.stages[_stageIndex - 1].id;
                        }
                    }
                });
                var complexDone = function () {
                    $.postJson(saveActivitySettingUrl, {
                            "activityCheckBoxId": $activityLi.attr('activityId'),
                            "checkFlg": ($lnk.attr('hasChecked') == 1 ? 0 : 1),
                            "winRate": winRate,
                            "stageId": postStageId,
                            "opportunityId": me._getCommonData().id
                        },
                        function (data) {
                            var dataJson = (data);
                            if (dataJson.status == 0 || dataJson.status == 1001) {
                                // 设定页面赢率,为1001说明赢率没有变
                                me.selfData.viewStageId = postStageId;
                                $.each(me.selfData.stages, function (_stageIndex, _stage) {
                                    var stageStatus = 1;
                                    var allUnChecked = 1;
                                    $.each(_stage.activities, function (_activityIndex, _activity) {
                                        if (_activity.id == $activityLi.attr('activityId')) {
                                            _activity.checked = ($lnk.attr('hasChecked') == 1 ? 0 : 1);
                                        }
                                        if (_activity.checked == 0) {
                                            stageStatus = 0;
                                        }
                                        if (_activity.checked == 1) {
                                            if (_activity.keyFlag == 1 && _activity.fileId == '') {
                                                stageStatus = 0;
                                            }
                                            allUnChecked = 0;
                                        }
                                    });
                                    _stage.stageStatus = stageStatus;
                                    //全取消要回到上一个阶段
                                    if (allUnChecked && _stage.id == $stageDiv.attr('stageId')) {
                                        if (_stageIndex > 0) {
                                            me.selfData.currentStage = me.selfData.stages[_stageIndex - 1];
                                            //me.selfData.viewStageId = me.selfData.currentStage.id;
                                        }
                                    } else if (!allUnChecked && _stage.id == $stageDiv.attr('stageId')) {
                                        me.selfData.currentStage = _stage;
                                        if (_stageIndex < me.selfData.stages.length - 1) {
                                            me.selfData.stages[_stageIndex + 1].stageStatus = 0;
                                        }
                                    }
                                });
                                //看看勾完之后的结果对前个阶段和后一个阶段的影响
                                me._renderComplexProgress();
                                if (needConfirm) {
                                    me._triggerOuterEvent('afterPopupEdit');
                                }
                            } else {
                                $.msg(rk.i18n('OPPORTUNITY_FLOW_SAVE_FAILED'));
                            }
                        });
                }
                if (needConfirm) {
                    $.confirm(rk.i18n('OPPORTUNITY_WIN_CONFIRM'), complexDone);
                } else {
                    complexDone();
                }
            });

            //初始化上传控件
            elem.on("click", "a.js-progress-file-upload", function () {
                //无修改权限不让点
                if (!me.selfData.canUpdate) {
                    return false;
                }
                //输单状态其它按钮不让点
                if(me.selfData.failureFlg == 1){
                    return false;
                }
                var $dialog = $($.format($.trim(require('platform/widgets/crm/opportunity/xsyOpportunityProgress/doc_upload.tpl'))));
                var $target = $(this);
                var $checkboxA = $target.parent().parent().find('a.xsy_opportunity_progress_flow_ico');
                if (!$checkboxA.hasClass("xsy_opportunity_progress_flow_done") && !$checkboxA.hasClass("xsy_opportunity_progress_flow_normal") && !$checkboxA.hasClass("js-can-upload")) {
                    return false;
                }
                $dialog.popup({
                    width: 460,
                    title: rk.i18n('CRM_CORE_UPLOAD_DOC'),
                    actions: {
                        upload: function(evt, dialog) {
                            var file = $dialog.find('.fileinput-box').singlefileuploader('val')[0];
                            if (!file) {
                                return $.msg(rk.i18n('CRM_CORE_SELECT_FILE_TO_UPLOAD'));
                            }
                            var activityId = $target.attr('activityId');
                            var postData = {
                                opportunityId: me._getCommonData().id,
                                activityId: activityId,
                                'opportunityProcessFile.fileUrl': file.url,
                                'opportunityProcessFile.fileName': file.name,
                                'opportunityProcessFile.size': file.size
                            };
                            $.postJson("/json/crm_opportunity/save-keyFile.action", postData).done(function(json) {
                                if (json.status == 0) {
                                    var $stageDiv = $target.closest('div[stageId]');
                                    me.selfData.viewStageId = $stageDiv.attr('stageId');
                                    $.each(me.selfData.stages, function (_stageIndex, _stage) {
                                        var stageStatus = 1;
                                        var allUnChecked = 1;
                                        $.each(_stage.activities, function (_activityIndex, _activity) {
                                            if (_activity.id == activityId) {
                                                _activity.fileId = json.fileId;
                                                _activity.fileName = json.fileName;
                                            }
                                            if (_activity.checked == 0) {
                                                stageStatus = 0;
                                            }
                                            if (_activity.checked == 1) {
                                                if (_activity.keyFlag == 1 && _activity.fileId == '') {
                                                    stageStatus = 0;
                                                }
                                                allUnChecked = 0;
                                            }
                                        });
                                        _stage.stageStatus = stageStatus;
                                        //全取消要回到上一个阶段
                                        if (allUnChecked && _stage.id == $stageDiv.attr('stageId')) {
                                            if (_stageIndex > 0) {
                                                me.selfData.currentStage = me.selfData.stages[_stageIndex - 1];
                                            }
                                        } else if (!allUnChecked && _stage.id == $stageDiv.attr('stageId')) {
                                            me.selfData.currentStage = _stage;
                                            if (_stageIndex < me.selfData.stages.length - 1) {
                                                me.selfData.stages[_stageIndex + 1].stageStatus = 0;
                                            }
                                        }
                                    });
                                    me._renderComplexProgress();
                                    dialog.destroy();
                                } else {
                                    $.msg(rk.i18n('USERSET_SERVER_ERR'));
                                }
                            }).fail(function(def, code, message) {
                                def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                            });
                        }
                    },
                    open: function(evt, ui) {
                        $dialog.find('.fileinput-box').singlefileuploader({
                            itemAdd: function() {
                                $dialog.popup('refresh');
                            },
                            itemRemove: function() {
                                $dialog.popup('refresh');
                            }
                        });
                    }
                });
            });

        }
    });
});